<?php

require_once "./vendor/autoload.php";

$url = 'http://www.3tempo.co.kr/product/list.html?cate_no=25';
$html = (new Request($url))->get();
(new ParseHtml($html))->parse();








class Request
{
    private $url;
    public function __construct($url)
    {
        $this->url = $url;
    }

    public function get()
    {
        $guzzle = new \GuzzleHttp\Client();
        $res = $guzzle->get($this->url);
        if ($res->getStatusCode() != 200)
            throw new MainException('request fail');

        return $res->getBody();
    }
}

class ParseHtml
{
    private $html;
    public function __construct($html)
    {
        $this->html = $html;
    }

    public function parse()
    {
        Draw::start();
        $dom = \Sunra\PhpSimple\HtmlDomParser::str_get_html($this->html);
        $recommends = $dom->find('.xans-product-listrecommend .prdList .item');
        Draw::line('BEST PRODUCT');
        foreach ($recommends as $recommend)
        {
            $this->item($recommend);
        }

        $normals = $dom->find('.xans-product-listnormal .prdList .item');
        Draw::line('NORMAL PRODUCT');
        foreach ($normals as $normal)
        {
            $this->item($normal);
        }
    }

    private function item(\simplehtmldom_1_5\simple_html_dom_node $item)
    {
        $_name_node = $item->find('.name a', 0);
        $href = $_name_node->href;
        $name = $_name_node->plaintext;

        $_parse = parse_url($href);
        $_query = $this->convertUrlQuery($_parse['query']);

        $product_no = $_query['product_no'];

        $price = $item->find('div ul li', 0)->find('span', 1)->innertext();
        $pic = $item->find('div a', 0)->find('img', 0)->getAttribute('src');

        Draw::draw($name, $price, $product_no, $href, $pic);
    }

    private function convertUrlQuery($query)
    {
        $queryParts = explode('&', $query);

        $params = array();
        foreach ($queryParts as $param)
        {
            $item = explode('=', $param);
            $params[$item[0]] = $item[1];
        }

        return $params;
    }
}

class Draw
{
    public static $_maxNameLength = 12;
    public static $_maxPriceLength = 12;
    public static $_maxProduct_noLength = 12;

    public function __construct()
    {
    }

    public static function start()
    {
        echo "\033[1A\n\033[K-----------------------\033[47;30m TASK START \033[0m-----------------------------\n\033[0m";
    }

    public static function line($title)
    {
        echo "\033[1A\n\033[K-----------------------\033[47;30m $title \033[0m-----------------------------\n\033[0m";
    }

    public static function draw($name, $price, $product_no, $href, $pic)
    {
        echo "name:$name\n";
        echo "price:$price\n";
        echo "product_no:$product_no\n";
        echo "href:$href\n";
        echo "pic:$pic\n\n";
    }
}

class MainException extends \Exception
{

}